<?php

namespace App\Http\Controllers;

use App\Models\Machine;
use App\Models\Product;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class PagesController extends Controller
{

    public function directShop()
    {
        session()->forget(['machine', 'product']);

        return view('front.shopping');
    }

    public function machineShop($machine_uuid)
    {
        //将微信用户转化成网站用户，并登陆
        if (!Auth::check()) {
            $this->dealUser();
        }
        $machine = Machine::query()->where('uuid', $machine_uuid)->first();
        session()->forget(['machine', 'product']);

        if ($machine instanceof Machine) {
            session(['machine' => $machine]);
            return view('front.shopping');
        } else {
            return '404,机器号错误';
        }

    }

    public function productShop($machine_uuid, $product_uuid)
    {
        //将微信用户转化成网站用户，并登陆
        if (!Auth::check()) {
            $this->dealUser();
        }

        $machine = Machine::query()->where('uuid', $machine_uuid)->first();
        session()->forget(['machine', 'product']);

        if ($machine instanceof Machine) {
            session(['machine' => $machine]);
            $product = Product::find($product_uuid);
            if ($product instanceof Product) {
                session(['product' => $product]);
                return view('front.shopping');
            } else {
                return '404,商品号错误，请联系管理员。';
            }
        } else {
            return '404,机器号错误，请联系管理员。';
        }
    }

    public function personal()
    {
        //将微信用户转化成网站用户，并登陆
        if (!Auth::check()) {
            $this->dealUser();
        }

        return view('front.personal');
    }

    public function dealUser()
    {
        $user = session('wechat.oauth_user.default');
        $userModel = User::query()->where('open_id', $user['id'])->first();
        if ($userModel instanceof User) {
            $userModel->update([
                'name' => $user['nickname'],
                'avatar' => $user['avatar'],
            ]);
            Auth::login($userModel);
            return $userModel;
        } else {
            $userModel = User::create([
                'open_id' => $user['id'],
                'name' => $user['nickname'],
                'avatar' => $user['avatar'],
            ]);
            Auth::login($userModel);
            return $userModel;
        }
    }
}
